﻿namespace System.Web.Mvc
{
    /// <summary>
    /// http://www.codehosting.net/blog/BlogEngine/post/More-fiddling-with-MVC3-and-https.aspx
    /// </summary>
    public class LimitHttpsFilter : IAuthorizationFilter
    {
        private static readonly Type Ssl = typeof(RequireHttpsAttribute);

        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.HttpContext != null && filterContext.HttpContext.Request != null)
            {
                if (!filterContext.HttpContext.Request.IsSecureConnection ||
                    filterContext.HttpContext.Request.IsAuthenticated)
                {
                    return;
                }
                if (!RequiresSSL(filterContext))
                {
                    filterContext.Result = Unencrypted(filterContext.HttpContext.Request);
                }
            }
        }

        private static bool RequiresSSL(AuthorizationContext filterContext)
        {
            return filterContext.ActionDescriptor != null && filterContext.ActionDescriptor.GetCustomAttributes(Ssl, true).Length > 0;
        }

        private static RedirectResult Unencrypted(HttpRequestBase request)
        {
            return new RedirectResult(request.Url.ToString().Replace("https:", "http:"));
        }
    }
}